﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Home
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.Events;
    using SharingCenter.Web.Classes.Messages;
    using SharingCenter.Web.Classes.enums;
    using SharingCenter.Web.Classes.Visits;
    using SharingCenter.Web.Classes.Profiles;
    using SharingCenter.Web.Classes.Groups;
    using SharingCenter.Web.Classes.Learning;

    public partial class Default : HomePageBase
    {
        protected WebProfile webProfile;
        protected Guid currentUserId;
        //protected aspnet_Membership memUser;
        protected string ta = string.Empty;
        protected Sc_Profile currentProfile;
        
        protected bool isMyPage = false;
        protected bool isContact = false;

        protected void Page_Init(object sender, EventArgs e)
        {
            //LinqDataSource1.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource1_Selecting);
            //LinqDataSource1.Selected += new EventHandler<LinqDataSourceStatusEventArgs>(LinqDataSource1_Selected);
            
            //VisitList1.VisitListObtained += new EventHandler<SharingCenter.Web.Shared.VisitListEventArgs>(VisitList1_VisitListObtained);
            if (Request.QueryString["id"] == null)
            {
                currentUserId = Profile.UserId;
            }
            else
            {
                currentUserId = new Guid(Request.QueryString["id"]);
            }
            using (scDataContext cxt = new scDataContext())
            {
                cxt.UpdateUserVisitCount(currentUserId);
            }
            
            ldsLearnings.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(ldsLearnings_Selecting);
        }

        void ldsLearnings_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            e.Result = LearningOperations.GetUserLearningProfile(currentUserId);
        }

        void VisitList1_VisitListObtained(object sender, SharingCenter.Web.Shared.VisitListEventArgs e)
        {
           // ltrVisitCount.Text = e.TotalVisits.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            currentProfile = ProfileOperations.GetProfile(currentUserId);

            if (currentProfile != null)
            {
                RenderInfo();
                List<Sc_Profile> l = new List<Sc_Profile>();
                l.Add(currentProfile);
                fvInfo.DataSource = l;
                fvInfo.DataBind();
                lvSide.DataSource = l;
                lvSide.DataBind();
                RenderGroups();
                RenderThreads();
            }
            else
            {
                RedirectToDefaultPage();
            }
        }

        void RenderInfo()
        {
            //memUser = currentProfile.aspnet_Membership;
            isMyPage = this.currentUserId == Profile.UserId;
            VisitOperations.AddVisit(EntityType.User, currentUserId, Profile.UserId);
            ta = currentUserId == Profile.UserId ? "我" : Utility.GetTa(this.currentProfile.Gender);
            isContact = Classes.Contact.ContactOperations.AreUsersContacts(currentUserId, Profile.UserId);
            CommentControl1.ContextId = currentUserId;
            RenderUser();
        }

        protected void MultiView1_PreRender(object sender, EventArgs e)
        {
            if (!isMyPage)
            {
                ((MultiView)sender).ActiveViewIndex = isContact ? 1 : 0;
            }
            else
            {
                ((MultiView)sender).Visible = false;
            }
        }
        void RenderGroups()
        {
            lvGroups.DataSource = GroupOperations.GetGroupsByUserId(currentUserId, true);
            lvGroups.DataBind();
        }

        protected void ltrHomeVisitCount_PreRender(object sender, EventArgs e)
        {
            
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            
        }

        void RenderUser()
        {
            RenderEvents();
        }

        private void RenderComments()
        {
            CommentControl1.ContextId = currentUserId;
        }

        void RenderEvents()
        {
            using (scDataContext cxt = new scDataContext())
            {
                List<Sc_Event> cevents = Classes.Events.EventOperations.GetEventsByCreatorUserId(currentUserId);
                var q = from item in cxt.Sc_Events
                        where item.StartDate > DateTime.Now && item.AdminApproved && item.CreatorUserId == this.currentUserId
                        select item;
                ltrCeCnt.Text = q.Count().ToString();
                lvEvents.DataSource = q.Take(10);
                lvEvents.DataBind();
                

                var p = from t in cxt.Sc_Events
                        from o in t.Sc_EventParticipants
                        where o.UserId == currentUserId && t.AdminApproved
                        orderby t.StartDate
                        select t;
                ltrJeCnt.Text = p.Count().ToString();
                lvJoinedEvents.DataSource = p.Take(10);
                lvJoinedEvents.DataBind();
                

                //ltrJeCnt.Text = p.Count().ToString();
                //lvJoinedEvents.DataSource = p;
                //lvJoinedEvents.DataBind();
            }
        }

        #region Page preparation
      

       

        ////bool GetMembershipUser()
        ////{
        ////    try
        ////    {
        ////        try
        ////        {
        ////            //dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, dataContext.Sc_Profiles.Single(d=>d.UserId==currentUserId));
        ////        }
        ////        catch { }
        ////        memUser = dataContext.aspnet_Memberships.Single(d => d.UserId == currentUserId);
        ////        ta = isMyPage ? "我" : Utility.GetTa(memUser.Sc_Profile.Gender);

        ////        isContact = Classes.Contact.ContactOperations.AreUsersContacts(Profile.UserId, currentUserId);
        ////    }
        ////    catch { return false; }

        ////    return true;
        ////}
        #endregion

        protected void AddContactAvatar_Load(object sender, EventArgs e)
        {
            ((Shared.ThumbAvatar)sender).UserId = currentUserId;
        }

        void ContactRequest(Guid userId2)
        {
            
            //MultiView mvContactRequest = (MultiView)fvInfo.FindControl("mvContactRequest");
            //TextBox txtRequestComment = (TextBox)mvContactRequest.FindControl("txtRequestComment");
            
        }

        void RenderThreads()
        {
            lvThreads.DataSource = PostOperations.GetUserThreads(currentUserId, 8, EntityType.Default);
            lvThreads.DataBind();
        }

        protected void ThreadLastUpdate_PreRender(object sender, EventArgs e)
        {
            Label s = (Label)sender;
            s.Text = Utility.FriendlyDateTime(s.Text, TimeDisplayEnum.LiteralHours, false);
        }
    }
}
